package org.ielts.repository.security;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.ielts.domain.security.Role;
import org.ielts.domain.security.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

@Repository
public class UserRoleRepository {

	@Autowired
	SessionFactory sessionFactory;

	public void removeUserFromRole(User user, Role role) {
		Session session = sessionFactory.getCurrentSession();

		session.load(user, user.getId());

		user.getRoles().remove(role);
	}

	public void addUserInRole(User user, Role role) {

		if (!user.getRoles().contains(role)) {
			user.getRoles().add(role);
		}
	}

	public Page<User> listUserInRole(Role role, String userName, Pageable pageable) {
		Session session = sessionFactory.getCurrentSession();

		Criteria criteria = session.createCriteria(User.class);
		criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		criteria.createAlias("roles", "r").add(Restrictions.eq("r.id", role.getId()));

		criteria.setFirstResult(pageable.getOffset());
		criteria.setMaxResults(pageable.getPageSize());

		if (StringUtils.isNotBlank(userName)) {
			criteria.add(Restrictions.like("name", userName));
		}
		@SuppressWarnings("unchecked")
		List<User> list = criteria.list();
		criteria.setFirstResult(0);

		criteria.setProjection(Projections.count("id"));
		Object object = criteria.uniqueResult();
		long total = (Long) object;

		Page<User> page = new PageImpl<User>(list, pageable, total);

		return page;
	}
}
